<template>
  <div>
    <search-cirteria
      v-model:name="queryParams.name"
      @search="query"
    />
    <div class="table-container">
      <table-operate>
        <n-button
          size="small"
          type="primary"
          @click="handleShowModal"
        >
          <template #icon>
            <n-icon :component="AddSharp" />
          </template>
          新增
        </n-button>
      </table-operate>
      <data-table
        :columns="columns"
        :data="list"
        :loading="loading"
      />

      <pagination
        :total="total"
        v-model:page-num="pageNum"
        v-model:page-size="pageSize"
        @update:pageNum="query"
        @update:pageSize="query"
      />
    </div>

    <modal-form
      v-model:show="visible"
      title="角色管理"
      :config="roleFormConifg"
      :width="550"
      :height="510"
      v-model:form="form"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h } from 'vue'
  import type { DataTableColumns, TreeSelectOption } from 'naive-ui'
  import type { Role, RoleDTO } from '@/api/power/role'
  import { AddSharp } from '@vicons/ionicons5'
  import { NButton, NFlex, NIcon } from 'naive-ui'
  import SearchCirteria from '@/components/SearchCriteria/index.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import TableOperate from '@/components/TableOperate/index.vue'
  import TableButton from '@/components/TableButton/index.vue'
  import ModalForm from '@/components/ModalForm/index.vue'
  import DictTag from '@/components/DictTag/index.vue'
  import DataTable from '@/components/DataTable/index.vue'

  import type { ModalFormConfig } from '@/components/ModalForm/index.vue'
  import { getMenuList } from '@/api/power/menu'
  import { addRole, getRoleList, getRole, updateRole, deleteRole } from '@/api/power/role'
  import { useCurd } from '@/hooks/useCrud'
  import { useDict } from '@/hooks/useDict'
  import { useMessage } from 'naive-ui'

  import { ListToTreeOption } from '@/utils/tool'
  import dayjs from 'dayjs'

  const message = useMessage()

  const { sys_common_status } = useDict('sys_common_status')

  // 窗口显示/隐藏
  const visible = ref(false)

  const form = ref<RoleDTO>({
    roleName: '',
    status: '1',
    sort: 1,
    menuIds: []
  })

  // 显示新增窗口
  const handleShowModal = async (id: any) => {
    if (typeof id === 'number') {
      const res = await getRole(id)
      form.value = res.data
    }
    visible.value = true
  }

  // 确认保存
  const handleConfirm = async () => {
    if (form.value.roleId) {
      const { roleId, ...arg } = form.value
      await updateRole(roleId, arg)
      message.success('修改角色成功')
    } else {
      await addRole(form.value)
      message.success('新增角色成功')
    }
    handleCancel()
    query()
  }

  const menuList = ref<TreeSelectOption[]>([])

  // 获取菜单列表
  const getMenus = async () => {
    const res = await getMenuList()
    menuList.value = ListToTreeOption(
      res.data,
      row => row.menuId,
      row => row.menuName
    )
  }

  // 取消保存
  const handleCancel = () => {
    form.value = {
      roleName: '',
      status: '1',
      sort: 1
    }
    visible.value = false
  }

  const { query, list, queryParams, total, pageNum, pageSize,loading, handleDelete } = useCurd<Role>({
    queryFn: getRoleList,
    deleteFn: deleteRole
  })

  onMounted(() => {
    getMenus()
  })

  const columns: DataTableColumns<Required<Role>> = [
    {
      title: '角色名称',
      key: 'roleName'
    },
    {
      title: '状态',
      key: 'status',
      render: row => h(DictTag, { options: sys_common_status.value, value: row.status })
    },
    {
      title: '排序',
      key: 'sort'
    },
    {
      title: '创建时间',
      key: 'createTime',
      align: 'center',
      render: row => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: 300,
      render(row) {
        return h(
          NFlex,
          { justify: 'center' },
          {
            default: () => [
              h(
                TableButton,
                {
                  type: 'primary',
                  onClick: () => handleShowModal(row.roleId)
                },
                {
                  default: () => '修改'
                }
              ),
              h(
                TableButton,
                {
                  type: 'error',
                  onClick: () => handleDelete(row.roleId)
                },
                {
                  default: () => '删除'
                }
              )
            ]
          }
        )
      }
    }
  ]

  const roleFormConifg = ref<ModalFormConfig[]>([
    {
      type: 'input',
      label: '角色名称',
      key: 'roleName',
      show: true
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      show: true,
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ]
    },
    {
      type: 'input-number',
      label: '排序',
      key: 'sort',
      show: true
    },
    {
      type: 'tree',
      label: '菜单选择',
      key: 'menuIds',
      span: 24,
      show: true,
      options: menuList
    }
  ])
</script>

<style scoped lang="scss"></style>
